package com.fun.feifun.modules.sys.auth.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fun.feifun.base.utils.common.ListUtil;
import com.fun.feifun.modules.sys.auth.dao.SysRoleMapper;
import com.fun.feifun.modules.sys.auth.model.SysMenu;
import com.fun.feifun.modules.sys.auth.model.SysRole;
import com.fun.feifun.modules.sys.auth.model.dto.RoleMenuDto;
import com.fun.feifun.modules.sys.auth.model.param.RoleMenuParam;
import com.fun.feifun.modules.sys.auth.service.ISysRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色 服务实现类
 * </p>
 *
 * @author wkf
 * @since 2022-04-21
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

	@Override
	public void setRoleMenus(Long roleId,List<Long> menuIds) {
		//先查询出来
		List<RoleMenuDto> roleMenuDtoList = baseMapper.getMenuByRoleId(roleId);

		List<Long> oldList = roleMenuDtoList.stream().map(it -> it.getMenuId()).collect(Collectors.toList());
		List<Long> newList = menuIds;
		//对比那些需要新增
		List<Long> insertList = ListUtil.getInsertList(newList ,oldList );
		if(!ListUtil.isEmpty(insertList)){
			List<RoleMenuDto> list=new ArrayList<>();
			for (Long menuId:insertList) {
				RoleMenuDto dto = new RoleMenuDto();
				dto.setRoleId(roleId);
				dto.setMenuId(menuId);
				list.add(dto);
			}
			int i = baseMapper.insertRoleMenus(list);
		}

		//对比那些需要删除
		List<Long> deleteList = ListUtil.getDeleteList(newList, oldList );
		if(!ListUtil.isEmpty(deleteList)){
			int i = baseMapper.deleteRoleMenus(roleId, deleteList);
		}

	}

	@Override
	public List<SysRole> getListByUser(List<Long> userIds) {
		List<SysRole> listByUserIds = baseMapper.getListByUserIds(userIds);
		return listByUserIds;
	}

	@Override
	public boolean saveRoleSetMenus(RoleMenuParam param) {
		SysRole role=param;
		boolean b = this.saveOrUpdate(role);
		if(!ListUtil.isEmpty(param.getMenuIds())){
			this.setRoleMenus(role.getId(),param.getMenuIds());
		}
		return b;
	}
}
